#!/usr/bin/python
#-*- coding UTF-8 -*-
import sys
import os
import re
import socket
import struct

def writeIDtoScreen(config):
    screenID = int(config['g_id'])
    rawID = screenID
    print screenID
    if config['arrow'] == 'up':
        arrow = 0xc0
    elif config['arrow'] == 'down':
        arrow = 0x80
    else:
        arrow = 0x40
    screenID = (screenID & 0x0000FFFF) | (arrow << 8)
    print "screen arrow and ID hex is %x" %screenID
    
    sock = config['ip']
    sock = sock.split(':')
    ip = sock[0]
    port = int(sock[1])
    addr = (ip,port)
    client = socket.socket()
    client.connect(addr)
    senddata = (0xaa,0x09,0x00,0xfe,0x10,(screenID>>8)&0xff,screenID&0xff,0x00,0x55)
    print senddata
    senddata = struct.pack('B'*len(senddata),*senddata)
    client.send(senddata)

    client.close()

def file_alter(file,old_line,new_line):
    with open(file,'r') as f1,open("%s.bak" % file,"w") as f2:
        for line in f1:
            if old_line in line:
                line = line.replace(old_line,new_line)
            f2.write(line)
    os.remove(file)
    os.rename("%s.bak" % file,file)

def parseline(config,line):
    ps = re.search('(\w+)\s+=\s+(\w+)',line)
    if ps:
        config[ps.groups()[0]] = ps.groups()[1]
    ps = re.search("(\w+)\s+=\s+(\d+\.\d+\.\d+\.\d+\s*:\s*\d+)",line)
    if ps:
        config[ps.groups()[0]] = ps.groups()[1]

if __name__ == '__main__':
    config = {}
    config_path = sys.argv[1]
    file = open(config_path,'rb')
    for line in file.readlines():
        if line.startswith(';'):
            continue
        ps = re.match('\[(\w+)\]',line)
        if ps:
            continue
        parseline(config,line)
    file.close()
    print config
    old_line = 'g_id = ' + config['g_id'] 
    writeIDtoScreen(config)
    rawID = int(config['g_id'])
    rawID = rawID + 1
    rawID = str(rawID)
    config['g_id'] = rawID
    new_line = 'g_id = ' + config['g_id']
    print "current ID %s \nnext ID %s" %(old_line,new_line)
    file_alter(config_path,old_line,new_line)
    
    